import service from '../common/service';
import { useMainStore } from '../store/modules/store';
import { bcmRequest, getBcmUrl, refreshToken } from './bcmServices';

const initbcmDict = async () => {
	const bcmUrl = getBcmUrl()
	let bcmDict = service.getLocalStorage('bcmDict');
	// console.log(bcmDict,'bcmDict')
	if (bcmDict) return;
	// service.enjoyShowLoading('正在加载字典...');
	const ret: any = await bcmRequest(bcmUrl.adminApi, '数据字典', 'EnjoyQueryList', {
		IsNotPage: true,
		WhereList: [
			{
				c_col: "dictName",
				c_logic: "而且",
				c_oper: "包含",
				c_value: "chnlType,orderStatus,deliveryStatus,pickType,deliveryTimeType,logisticsCode,afsOrderStatus,afsOrderStatus,dealType,returnGoodsType,orderCancelReasonType,rejectOrderCancelApplyType,deliveryCancelReasonType,rejectReasonType,performanceStatus,orderPrimaryStatus,rejectAfsApplyOrder,afsRejectInBound,stockoutRecoveryMethod,deliveryPlatformType"
			},
			{
			c_col: "status",
			c_oper: "等于",
			c_value: "1",
			c_logic: "而且",
			c_col_dtype: "System.String"
		}],
	});
	let _bcmSysDict: any = {};
	ret.ReturnObject.forEach((element: any) => {
		let items = []
		if (element.dictItemList != null) {
			items = element.dictItemList?.map((m: any) => ({
				text: m.dictItemText,
				label: m.dictItemText,
				value: m.dictItemValue,
				pdict: m.pDictItemValue,
				remark: m.remark,
				styleType: element?.dictStyleType,
				bgcolor: colorToRgba(m.dictItemColor, 0.05),
				bordercolor: colorToRgba(m.dictItemColor, 0.4),
				color: colorToRgba(m.dictItemColor, 1),
				sort: m.sort
			}));
		}
		_bcmSysDict[element.dictName] = {
			// ...element,
			dictId: element.dictId,
			dictName: element.dictName,
			dictTitle: element.dictTitle,
			isShowDesc: element.isShowDesc,
			dictStyleType: element.dictStyleType,
			dataItems: items?.sort((a: any, b: any) => Number(a.sort) - Number(b.sort))
		}
	});
	service.addlocalStorage('bcmDict', _bcmSysDict);
};

const colorToRgba = (sHex: string, alpha = 1) => {
	// ⼗六进制颜⾊值的正则表达式
	var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
	/* 16进制颜⾊转为RGB格式 */
	let sColor = sHex?.toLowerCase()
	if (sColor && reg.test(sColor)) {
		if (sColor.length === 4) {
			var sColorNew = '#'
			for (let i = 1; i < 4; i += 1) {
				sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
			}
			sColor = sColorNew
		}
		//  处理六位的颜⾊值
		var sColorChange = []
		for (let i = 1; i < 7; i += 2) {
			sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
		}
		return 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
	} else {
		return sColor
	}
}

const init = async () => {
	await refreshToken();
	await initbcmDict();
}

const getWorkStatus = async () => {
	const bcmUrl = getBcmUrl()
	const { loginInfo, setWorkStatus } = useMainStore()
	if (!loginInfo?.workStatus) {
		const ret: any = await bcmRequest(bcmUrl.stockApi, '用户表', 'EnjoyQueryList', {
			IsNotPage: false,
			CurrentPage: 1,
			PageSize: 1,
			WhereList: [{
				c_col: "userno",
				c_oper: "等于",
				c_value: loginInfo.sUser,
				c_logic: "而且",
				c_col_dtype: "System.String"
			}],
		});
		if (ret.ReturnObject?.length) {
			setWorkStatus(ret.ReturnObject[0].workStatus)
			return ret.ReturnObject[0].workStatus
		}
	}
}

const getDefaultMerchantInfo = async () => {
	const { loginInfo, setUserDefaultMerchantInfo } = useMainStore()
	const bcmUrl = getBcmUrl();
	const response: any = await bcmRequest(bcmUrl.stockApi, '用户表', 'EnjoyQueryList', {
		IsNotPage: false,
		WhereList: [{
			c_col: "extras",
			c_logic: "而且",
			c_oper: "等于",
			c_value: JSON.stringify({
				isQueryMerchantLink: true
			})
		}, {
			c_col: "userno",
			c_logic: "而且",
			c_oper: "等于",
			c_value: loginInfo.sUser
		}]
	});
	if (response.ReturnObject?.length) {
		if (!!response.ReturnObject[0].merchantCode){
			setUserDefaultMerchantInfo({
				merchantCode: response.ReturnObject[0].merchantCode,
				merchantName: response.ReturnObject[0].merchantName,
			})
		}
	}
}

const clearBcmLocalStorage = async (key = '') => {
	if (key) {
		await service.removeStorageSync(key);
		return;
	};
	await service.removeStorageSync('bcmDict');
}

const onClickRefresh = async () => {
	// 清除缓存
	await clearBcmLocalStorage('');
	// 初始化缓存
	await init();
}

export {
	init,
	initbcmDict,
	onClickRefresh,
	clearBcmLocalStorage,
	getWorkStatus,
	getDefaultMerchantInfo
};